'use strict';
const https = require('https');
const crypto = require('crypto');

// === 关键配置参数 ===
const CONFIG = {
  QUERY_WINDOW: 300000,      // 5分钟查询窗口
  PLATFORM_DELAY: 30000,      // 30秒平台延迟
  MAX_ATTEMPTS: 5,            // 最大重试次数
  
  DEVICE_CONFIG: {
    productKey: 'k25es2SPWFj',
    deviceName: 'device1',
    properties: [
      { identifier: 'LightLux', type: 'int', range: [0, 4095] },
      { identifier: 'Humidity', type: 'float', range: [0, 100] },
      { identifier: 'soilHumidity', type: 'int', range: [0, 4095], convertToPercent: true },
      { identifier: 'temperature', type: 'float', range: [-40, 80] }
    ]
  },
  
  ALIYUN_API: {
    accessKeyId: process.env.ACCESS_KEY_ID || 'LTAI5tHEAG3GCHuV1gzoSzge',
    accessKeySecret: process.env.ACCESS_KEY_SECRET || 'fv6cpr8EyjVnsUMWFLmZYXbcBfgVCq',
    endpoint: 'iot.cn-shanghai.aliyuncs.com',
    regionId: 'cn-shanghai',
    apiVersion: '2018-01-20'
  }
};

// Node.js兼容性处理 - 保留完整兼容性代码
if (typeof global.TextDecoder === 'undefined') {
  try {
    const util = require('util');
    global.TextDecoder = util.TextDecoder;
    global.TextEncoder = util.TextEncoder;
  } catch (e) {
    console.warn('TextDecoder/TextEncoder不可用:', e.message);
  }
}

/**
 * 数值转换与验证
 */
const convertAndValidateValue = (rawValue, prop) => {
  try {
    let numValue = rawValue;
    if (typeof rawValue === 'string') {
      numValue = parseFloat(rawValue.replace('%', '').replace('!', ''));
    }
    
    let value = prop.type === 'int' ? parseInt(numValue) : numValue;
    
    if (prop.convertToPercent && prop.identifier === 'soilHumidity') {
      const [min, max] = prop.range;
      value = Math.round((value / (max - min)) * 100);
    }
    
    if (prop.range && (value < prop.range[0] || value > prop.range[1])) {
      console.warn(`数值超出范围: ${prop.identifier}=${value}`);
      return null;
    }
    
    return isNaN(value) ? null : value;
  } catch (error) {
    console.error(`数值转换错误(${prop.identifier}):`, error);
    return null;
  }
};

/**
 * 生成阿里云API签名
 */
function signAliyunRequest(accessKeySecret, parameters) {
  // 按参数名称排序
  const sortedKeys = Object.keys(parameters).sort();
  
  // 构建规范化的查询字符串
  const canonicalizedQueryString = sortedKeys.map(key => {
    return `${encodeURIComponent(key)}=${encodeURIComponent(parameters[key])}`;
  }).join('&');
  
  // 构造待签名字符串
  const stringToSign = `GET&%2F&${encodeURIComponent(canonicalizedQueryString)}`;
  
  // 使用HMAC-SHA1算法签名
  const hmac = crypto.createHmac('sha1', `${accessKeySecret}&`);
  hmac.update(stringToSign);
  
  return hmac.digest('base64');
}

/**
 * 发送阿里云API请求
 */
const sendAliyunRequest = async (apiParams) => {
  return new Promise((resolve, reject) => {
    const requestParams = {...apiParams};
    
    // 生成签名
    requestParams.Signature = signAliyunRequest(
      CONFIG.ALIYUN_API.accessKeySecret,
      requestParams
    );
    
    // 构建查询字符串
    const queryString = Object.entries(requestParams)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const url = `https://${CONFIG.ALIYUN_API.endpoint}/?${queryString}`;
    
    console.log(`准备发送API请求: ${url.substring(0, 100)}...`);
    
    const options = {
      method: 'GET',
      timeout: 10000, // 10秒超时
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };
    
    const req = https.get(url, options, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        if (res.statusCode === 200) {
          try {
            const response = JSON.parse(data);
            resolve(response);
          } catch (e) {
            console.error('响应解析失败:', e.message);
            reject(new Error(`响应解析失败: ${e.message}`));
          }
        } else {
          let errorMsg = `API错误 ${res.statusCode}: ${data.substring(0, 200)}`;
          
          if (res.statusCode === 400 && data.includes('SignatureDoesNotMatch')) {
            errorMsg += ' (签名不匹配，请检查accessKeySecret)';
          }
          
          console.error(errorMsg);
          reject(new Error(errorMsg));
        }
      });
    });
    
    req.on('error', (err) => {
      console.error('请求失败:', err.message);
      reject(err);
    });
    
    req.on('timeout', () => {
      console.error('请求超时');
      req.destroy();
      reject(new Error('请求超时'));
    });
  });
};

// 云函数入口
exports.main = async (event, context) => {
  const startTime = Date.now();
  
  const result = {
    code: 200,
    message: 'success',
    data: {},
    timestamps: {},
    meta: {
      startTime: new Date(startTime).toISOString()
    }
  };

  try {
    console.log(`==== 开始执行云函数 [${new Date().toISOString()}] ====`);
    console.log('使用的ACCESS_KEY:', CONFIG.ALIYUN_API.accessKeyId);
    
    // 计算查询时间范围（UTC时间）
    const utcNow = Date.now();
    const endTime = utcNow - CONFIG.PLATFORM_DELAY;
    const startTimeQuery = endTime - CONFIG.QUERY_WINDOW;
    
    // 转换为阿里云要求的精确时间格式 (YYYY-MM-DDTHH:mm:ssZ)
    const toIsoString = (date) => {
      return new Date(date).toISOString()
        .replace(/\.\d{3}Z$/, 'Z');
    };
    
    const isoStartTime = toIsoString(startTimeQuery);
    const isoEndTime = toIsoString(endTime);
    
    console.log('有效的查询时间范围(UTC):', {
      start: isoStartTime,
      end: isoEndTime,
      duration: `${CONFIG.QUERY_WINDOW/1000}秒`
    });
    
    console.log('有效的查询时间范围(北京时间):', {
      start: new Date(startTimeQuery + 8 * 3600000).toISOString(),
      end: new Date(endTime + 8 * 3600000).toISOString()
    });

    // 并行查询所有属性
    const queries = CONFIG.DEVICE_CONFIG.properties.map(async (prop) => {
      try {
        console.log(`查询属性: ${prop.identifier}`);
        
        // 构造API参数 - 严格遵守阿里云API要求
        const apiParams = {
          Action: 'QueryDevicePropertyData',
          Format: 'JSON',
          RegionId: CONFIG.ALIYUN_API.regionId,
          AccessKeyId: CONFIG.ALIYUN_API.accessKeyId,
          SignatureMethod: 'HMAC-SHA1',
          SignatureVersion: '1.0',
          SignatureNonce: `${Date.now()}-${Math.floor(Math.random() * 10000)}`,
          Timestamp: new Date().toISOString().replace(/\.\d+/, ''),
          Version: CONFIG.ALIYUN_API.apiVersion,
          
          // 设备参数 - 大小写敏感
          ProductKey: CONFIG.DEVICE_CONFIG.productKey,
          DeviceName: CONFIG.DEVICE_CONFIG.deviceName,
          Identifier: prop.identifier,
          Asc: '0', // 0表示按时间倒序
          PageSize: '10', // 获取10条记录
          
          // 阿里云要求的时间格式：YYYY-MM-DDTHH:mm:ssZ
          StartTime: isoStartTime,
          EndTime: isoEndTime
        };
        
        // 发送API请求
        const response = await sendAliyunRequest(apiParams);
        
        // 处理响应
        const records = (response?.Data?.List?.PropertyInfo) || [];
        console.log(`属性 ${prop.identifier} 获取记录数: ${records.length}`);
        
        // 查找最近的有效值
        let foundRecord = null;
        for (let record of records) {
          if (record.Time && record.Value !== undefined) {
            const value = convertAndValidateValue(record.Value, prop);
            if (value !== null) {
              foundRecord = {
                identifier: prop.identifier,
                value,
                timestamp: record.Time
              };
              break;
            }
          }
        }
        
        if (foundRecord) {
          console.log(`属性 ${prop.identifier} 找到有效值: ${foundRecord.value}`);
          return foundRecord;
        } else {
          console.warn(`无有效记录: ${prop.identifier}`);
          return null;
        }
      } catch (error) {
        const errorMsg = `查询属性失败(${prop.identifier}): ${error.message || '未知错误'}`;
        console.error(errorMsg);
        console.error('错误详情:', error);
        return {
          identifier: prop.identifier,
          error: errorMsg,
          code: 'API_ERROR'
        };
      }
    });
    
    // 等待所有查询完成
    const results = await Promise.all(queries);
    
    // 处理有效结果
    let validDataCount = 0;
    result.errors = {};
    
    results.forEach(item => {
      if (item && item.value !== null) {
        result.data[item.identifier] = item.value;
        result.timestamps[item.identifier] = item.timestamp;
        validDataCount++;
      } else if (item && item.error) {
        result.errors[item.identifier] = item.error;
      }
    });
    
    // 设置最终状态
    if (validDataCount === 0) {
      result.code = 503;
      result.message = '未获取到有效数据';
    } else if (validDataCount < CONFIG.DEVICE_CONFIG.properties.length) {
      result.code = 206;
      result.message = `部分数据缺失 (${validDataCount}/${CONFIG.DEVICE_CONFIG.properties.length})`;
    }

  } catch (globalError) {
    console.error('[全局错误]', globalError);
    result.code = 500;
    result.error = `服务器错误: ${globalError.message}`;
  }
  
  // 添加执行时间
  result.meta.endTime = new Date().toISOString();
  result.meta.executionTime = `${Date.now() - startTime}ms`;
  
  console.log(`==== 结束执行云函数 (${result.meta.executionTime}) ====`);
  console.log('最终结果:', JSON.stringify({
    code: result.code,
    message: result.message,
    dataCount: Object.keys(result.data).length,
    errorCount: Object.keys(result.errors).length
  }, null, 2));
  
  return result;
};